package com.ly.controller;

import com.ly.pojo.EdocCategory;
import com.ly.pojo.EdocEntry;
import com.ly.service.EdocEntryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
public class EdocEntrtController {
    @Autowired
    private EdocEntryService edocEntryService;

    @GetMapping("/")
    public String redirectToEdocList() {
        return "redirect:/list";
    }

    @GetMapping("/add")
    public String toAdd() {
        return "add";
    }

    @PostMapping("/add")
    public String add(EdocEntry edocEntry) {
        Integer add = edocEntryService.add(edocEntry);
        if(add>0){
            return "redirect:/list";
        }
        return "add";
    }


    @GetMapping("/list")
    public String list(Model model,
                       @RequestParam(required = false) Integer categoryId,
                       @RequestParam(defaultValue = "1") Integer startIndex,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        List<EdocEntry> list = edocEntryService.list(categoryId, startIndex, pageSize);
        Long count = edocEntryService.count(categoryId);
        long pageCount = count / pageSize;
        if (count % pageSize != 0) {
            pageCount += 1;
        }

        model.addAttribute("list", list);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("startIndex",startIndex);
        model.addAttribute("pageCount",pageCount);
        return "list";
    }

    @GetMapping("/categoryList")
    @ResponseBody
    public List<EdocCategory> list() {
        return edocEntryService.categoryList();
    }

    @GetMapping("/selectById")
    public String selectById(Model model, Integer id) {
        EdocEntry edocEntry = edocEntryService.getById(id);
        model.addAttribute("ed", edocEntry);
        return "update";
    }

    @PostMapping("/update")
    public String update(EdocEntry edocEntry) {
        if(edocEntryService.update(edocEntry)>0){
            return "redirect:/list";
        }
        return "error";
    }

    @GetMapping("/delete")
    public String del(Integer id) {
        if(edocEntryService.delete(id)>0){
            return "redirect:/list";
        }
        return "error";
    }
}
